package com.ilink.teacherservice.service.impl.xiaolian;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.teacherservice.entity.PO.xiaolian.XiaolianConversationLogs;
import com.ilink.teacherservice.mapper.xiaolian.XiaolianConversationLogsMapper;
import com.ilink.teacherservice.service.xiaolian.XiaolianConversationCountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class XiaolianConversationCountServiceImpl extends ServiceImpl<XiaolianConversationLogsMapper, XiaolianConversationLogs> implements XiaolianConversationCountService {

    private static final Logger logger = LoggerFactory.getLogger(XiaolianConversationCountServiceImpl.class);

    @Autowired
    private XiaolianConversationLogsMapper conversationLogsMapper;

    /**
     * 获取所有对话记录及其回答次数，并根据传入的 courseFileId 进行匹配
     *
     * @param courseFileId 课程文件ID (Long 类型)
     * @return 返回所有对话记录及其对应的次数
     */
    @Override
    public List<Map<String, Object>> getAllConversationLogsWithCount(Long courseFileId) {
        // 输出接收到的 courseFileId
        logger.info("Received courseFileId: {}", courseFileId);


        // 查询所有对话记录/
        List<XiaolianConversationLogs> allLogs = conversationLogsMapper.selectList(new QueryWrapper<>());
        logger.info("Total conversation logs fetched: {}", allLogs.size());


        List<XiaolianConversationLogs> matchedLogs;

        // 如果 courseFileId 为 null，则返回所有记录并进行统计
        if (courseFileId == null) {
            matchedLogs = allLogs;  // 如果没有指定 courseFileId，返回所有记录
            logger.info("No courseFileId provided, returning all logs.");
        } else {
            // 过滤出匹配 courseFileId 的记录
            matchedLogs = allLogs.stream()
                    .filter(log -> {
                        String courseFilePath = log.getCourseFilePath();
                        // 如果 courseFilePath 不为空并且匹配 courseFileId
                        return courseFilePath != null && isMatchingCourseFileId(courseFilePath, courseFileId);
                    })
                    .collect(Collectors.toList());
            logger.info("Total matched logs for courseFileId '{}' : {}", courseFileId, matchedLogs.size());
        }

        // 按 userInput 分组，并去掉 userInput 中的换行符和多余的空格
        Map<String, List<String>> groupedLogs = matchedLogs.stream()
                .collect(Collectors.groupingBy(
                        log -> log.getUserInput().trim().replaceAll("\\s+", " "), // 去除换行符和多余空格
                        Collectors.mapping(XiaolianConversationLogs::getAssistantReply, Collectors.toList())
                ));

        logger.info("Grouped matched logs by user input: {}", groupedLogs);

        // 创建结果列表
        List<Map<String, Object>> result = new ArrayList<>();

        // 遍历每个问题并统计相关信息
        for (Map.Entry<String, List<String>> entry : groupedLogs.entrySet()) {
            String userInput = entry.getKey();
            List<String> assistantReplies = entry.getValue();

            logger.debug("Processing userInput: {}", userInput);
            logger.debug("Number of replies for this input: {}", assistantReplies.size());

            // 构造返回的数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userInput", userInput);  // 问题（已清理）
            resultMap.put("count", assistantReplies.size());  // 问题的回答次数
            resultMap.put("answers", assistantReplies);  // 回答内容列表

            // 添加到结果列表
            result.add(resultMap);
        }

        logger.info("Returning {} result maps.", result.size());
        return result;
    }

    /**
     * 判断文件路径中是否包含匹配的 courseFileId
     *
     * @param courseFilePath 课程文件路径
     * @param courseFileId 课程文件ID (Long 类型)
     * @return 是否匹配
     */
    private boolean isMatchingCourseFileId(String courseFilePath, Long courseFileId) {
        // 假设 courseFilePath 格式类似于 "/files/{courseFileId}.mp4"
        // 需要从 courseFilePath 中提取出文件ID进行比较
        logger.debug("Checking if courseFilePath '{}' matches courseFileId '{}'", courseFilePath, courseFileId);

        String[] parts = courseFilePath.split("/");
        if (parts.length > 1) {
            String fileIdFromPath = parts[1];  // 提取文件ID（如 12345）

            logger.debug("Extracted fileIdFromPath: {}", fileIdFromPath);

            // 判断提取的文件ID是否与传入的 courseFileId 匹配
            return fileIdFromPath.equals(courseFileId.toString());
        }
        return false;
    }
}
